package com.fable.web.controller.keyword;

import com.alibaba.fastjson.JSON;
import com.fable.biz.operate.CreateKeywordModel;
import com.fable.common.config.RequireLogin;
import com.fable.common.utils.JsonResult;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.mapper.ext.KeywordExtMapper;
import com.fable.dal.model.KeywordDO;
import com.fable.dal.model.KeywordQuery;
import com.fable.web.common.admin.UserTools;
import com.fable.web.common.annotation.Track;
import com.fable.web.page.P;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by weishuai on 18/7/21.
 */
@Controller
@RequireLogin
@RequestMapping("/keyword")
public class KeywordController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    KeywordExtMapper keywordExtMapper;

    @RequestMapping("/keywordList.htm")
    @Track(tag= P.UrlEnum.addCustomer)
    public String list(ModelMap model, HttpSession session) {
        KeywordQuery query = new KeywordQuery();
        query.setOrderByClause(" id desc ");
        KeywordQuery.Criteria criteria = query.createCriteria();
        criteria.andStatusGreaterThanOrEqualTo("0");
        AdminUserDTO adminUserDTO = UserTools.getAdminUser(session);
        if (!"admin".equals(adminUserDTO.getRoleName())) {
            criteria.andAdminIdEqualTo(Integer.parseInt(UserTools.getLoginId(session).toString()));
        }
        List<KeywordDO> list = keywordExtMapper.selectByQuery(query);
        model.put("list", list);
        return "keyword/keywordList";
    }


    @RequestMapping("/keywordAdd.htm")
    public String add(HttpServletRequest request, ModelMap model, Integer id) {
        //id不为空则说明是点击修改过来的

        if (id != null) {
            KeywordDO keywordDO = keywordExtMapper.selectByPrimaryKey(id);
            model.put("result", keywordDO);
        }
        return "keyword/keywordAdd";
    }

    @RequestMapping("/delKeyword.json")
    @Track(tag= P.UrlEnum.delKeyword)
    @ResponseBody
    public JsonResult delete(HttpServletRequest request, Integer id) {
        JsonResult result = new JsonResult();
        if (id != null) {
            KeywordDO keywordDO = keywordExtMapper.selectByPrimaryKey(id);
            if (keywordDO == null) {
                result.setErrMsg("对象不存在!");
                return result;
            } else {
                keywordDO.setStatus("-1");
                keywordExtMapper.updateByPrimaryKeySelective(keywordDO);
            }
        }
        return result;
    }


    @RequestMapping("/saveKeyword.json")
    @Track(tag= P.UrlEnum.saveKeyword)
    @ResponseBody
    public JsonResult saveAdminUser(@ModelAttribute CreateKeywordModel createKeywordModel, HttpSession session) {
        JsonResult jsonResult = new JsonResult();
        try {

            if (createKeywordModel.getId() != null) {
                KeywordDO keywordDO = keywordExtMapper.selectByPrimaryKey(createKeywordModel.getId());
                if (keywordDO == null) {
                    logger.error("非法操作,param:{}", JSON.toJSONString(createKeywordModel));
                    jsonResult.setErrMsg("非法操作!");
                    return jsonResult;
                }
                keywordDO.setGmtModified(new Date());
                keywordDO.setGmtCreate(new Date());
                BeanUtils.copyProperties(createKeywordModel, keywordDO);
                keywordExtMapper.updateByPrimaryKeySelective(keywordDO);
            } else {
                if (checkExist(createKeywordModel)) {
                    jsonResult.setErrMsg("已存在相同手机号码用户!");
                    return jsonResult;
                }
                KeywordDO keywordDO = new KeywordDO();
                BeanUtils.copyProperties(createKeywordModel, keywordDO);
                keywordDO.setGmtModified(new Date());
                keywordDO.setAdminId(Integer.parseInt(UserTools.getLoginId(session).toString()));
                keywordExtMapper.insertSelective(keywordDO);
            }
        } catch (Exception e) {
            logger.error("保存人才异常,param:{}", JSON.toJSONString(createKeywordModel), e);
            jsonResult.setErrMsg("保存异常请联系管理员!");
            return jsonResult;
        }
        return jsonResult;
    }


    private boolean checkExist(@ModelAttribute CreateKeywordModel createKeywordModel) {
        KeywordQuery query = new KeywordQuery();
        query.createCriteria().andStatusGreaterThanOrEqualTo("0").andWordEqualTo(createKeywordModel.getWord());
        List<KeywordDO> list = keywordExtMapper.selectByQuery(query);
        if (!CollectionUtils.isEmpty(list)) {
            logger.warn("已存在关键词,param:{}", JSON.toJSONString(createKeywordModel));
            return true;
        }
        return false;
    }

}
